<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<button class="back-arrow" @click="goBack"></button>
			<p>地址管理</p>
		</header>
		<!-- 地址列表部分 -->
		<ul class="addresslist">
			<li v-for="item in deliveryAddressArr">
				<div class="addresslist-left" @click="setDeliveryAddress(item)">
					<h3>{{item.contactName}}{{item.contactSex | sexFilter}} {{item.contactTel}}
					</h3>
					<p>{{item.address}}</p>
				</div>
				<div class="addresslist-right">
					<i class="fa fa-edit" @click="editUserAddress(item.daId)"></i>
					<i class="fa fa-remove" @click="removeUserAddress(item.daId)"></i>
				</div>
			</li>
		</ul>
		<!-- 新增地址部分 -->
		<div class="addbtn" @click="toAddUserAddress">
			<i class="fa fa-plus-circle"></i>
			<p>新增收货地址</p>
		</div>
		 <!-- Alert Modal -->
		 <alert-modal v-if="alertVisible" :visible.sync="alertVisible" :message="alertMessage"></alert-modal>
		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>
<script>
	import Footer from '../components/Footer.vue';
    import AlertModal from '../views/AlertModal.vue';
	import JSEncrypt from 'jsencrypt';
	import request from '../request.js';
	export default {
		name: 'UserAddress',
		data() {
			return {
				businessId: this.$route.query.businessId,
				user: {},
				deliveryAddressArr: [],
				alertVisible: false,
		        alertMessage: ''
			}
		},
		created() {
			this.user = this.$getSessionStorage('user');

			this.listDeliveryAddressByUserId();
		},
		components: {
			Footer,AlertModal
		},
		filters: {
			sexFilter(value) {
				return value == 1 ? '先生' : '女士';
			}
		},
		methods: {
			goBack() {
		   		console.log('Trying to go back...');
		   		this.$router.go(-1); // 相当于浏览器的后退操作
	       	},
			listDeliveryAddressByUserId() {
  				// 生成RSA密钥对
  				const rsa = new JSEncrypt();
  				const keypair = rsa.getKey();

  				// 获取公钥和私钥
  				const publicKeyPem = keypair.getPublicKey();
  				const privateKeyPem = keypair.getPrivateKey();
  				const publicKey = publicKeyPem.replace(/-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----|\n/g, '');
				const privateKey = privateKeyPem.replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\n/g, '');
  				// 发起请求获取加密的送货地址信息
  				request.get('delivery-addresses/users/', {
    				params: {
      					userId: this.user.userId,
      					publicKey: publicKey
    				}
  				}).then(response => {
    			this.deliveryAddressArr = response.data;
    			// 遍历地址数组，对每个地址的联系电话和地址信息进行解密
    			this.deliveryAddressArr.forEach(address => {
      				const encryptor = new JSEncrypt();
      				encryptor.setPrivateKey(privateKey); // 设置私钥
      				address.contactTel = encryptor.decrypt(address.contactTel) ; // 解密手机号
      				address.address = encryptor.decrypt(address.address) ; // 解密地址
    				});
  				}).catch(error => {
    				console.error(error);
  				});
			},
			setDeliveryAddress(deliveryAddress) {
				//把用户选择的默认送货地址存储到localStorage中
				this.$setLocalStorage(this.user.userId, deliveryAddress);
				this.$router.push({
					path: '/orders',
					query: {
						businessId: this.businessId
					}
				});
			},
			toAddUserAddress() {
				this.$router.push({
					path: '/addUserAddress',
					query: {
						businessId: this.businessId
					}
				});
			},
			editUserAddress(daId) {
				this.$router.push({
					path: '/editUserAddress',
					query: {
						businessId: this.businessId,
						daId: daId
					}
				});
			},
			removeUserAddress(daId) {
				if (!confirm('确认要删除此送货地址吗？')) {
					return;
				}

				request.delete(`delivery-addresses/${daId}`).then(response => {
					if (response.data > 0) {
						let deliveryAddress = this.$getLocalStorage(this.user.userId);
						if (deliveryAddress != null && deliveryAddress.daId == daId) {
							this.$removeLocalStorage(this.user.userId);
						}
						this.listDeliveryAddressByUserId();
					} else {
						this.alertMessage ='删除地址失败！';
						this.alertVisible = true;
					}
				}).catch(error => {
					console.error(error);
				});
			}
		}
	}
</script>
<style scoped>
	/*************** 总容器 ***************/
	.wrapper {
		width: 100%;
		height: 100%;
		background-color: #F5F5F5;
	}
    /****************** 返回键 ******************/
 .back-arrow {
	position: fixed; /* 固定定位 */
	left: 10px; /* 距离屏幕左端像素 */
	top: 1.5px; /* 距离屏幕顶部像素 */
	width: 50px; /* 宽度 */
	height: 50px; /* 高度 */
	background-color: rgba(0, 151, 255, 0.5); /* 半透明的背景颜色 */
	display: flex;
	justify-content: center;
	align-items: center;
	cursor: pointer;
	border: none; /* 隐藏边框 */
	transition: background-color 0.3s ease; /* 背景颜色变化动画 */
  }
  
  .back-arrow::before {
	content: '\f053'; /* 使用 FontAwesome 的左箭头图标 */
	font-family: 'FontAwesome'; /* FontAwesome 字体 */
	font-size: 24px; /* 字体大小 */
	color: #fff; /* 字体颜色 */
	transition: color 0.3s ease; /* 字体颜色变化动画 */
  }
  
  .back-arrow:hover::before {
	color: #0a2ddc; /* 保持原有的颜色或根据需要进行调整 */
  }
  
  .back-arrow:hover {
	background-color: rgba(0, 151, 255, 0.3); /* 鼠标悬停时的背景颜色变化为更透明 */
  }
	/*************** header ***************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		display: flex;
		justify-content: space-around;
		align-items: center;
		color: #fff;
		font-size: 4.8vw;
		position: fixed;
		left: 0;
		top: 0;
		/*保证在最上层*/
		z-index: 1000;
	}

	/*************** addresslist ***************/
	.wrapper .addresslist {
		width: 100%;
		margin-top: 12vw;
		background-color: #fff;
	}

	.wrapper .addresslist li {
		width: 100%;
		box-sizing: border-box;
		border-bottom: solid 1px #DDD;
		padding: 3vw;
		display: flex;
	}

	.wrapper .addresslist li .addresslist-left {
		flex: 5;
		/*左边这块区域是可以点击的*/
		user-select: none;
		cursor: pointer;
	}

	.wrapper .addresslist li .addresslist-left h3 {
		font-size: 4.6vw;
		font-weight: 300;
		color: #666;
	}

	.wrapper .addresslist li .addresslist-left p {
		font-size: 4vw;
		color: #666;
	}

	.wrapper .addresslist li .addresslist-right {
		flex: 1;
		font-size: 5.6vw;
		color: #999;
		cursor: pointer;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	/*************** 新增地址部分 ***************/
	.wrapper .addbtn {
		width: 100%;
		height: 14vw;
		border-top: solid 1px #DDD;
		border-bottom: solid 1px #DDD;
		background-color: #fff;
		margin-top: 4vw;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 4.5vw;
		color: #0097FF;
		user-select: none;
		cursor: pointer;
	}

	 .wrapper .addbtn p {
		margin-left: 2vw;
	}
</style>